//testing

var g_cooraddr;

function restCall(url){
	var req = new XMLHttpRequest();
	req.open("GET", url, false); 
	req.send(null);
	
	if(req.status == 200)
      return req.responseXML;
     else
      throw "GET "+ url + " failed with status "+ req.status + " "+ req.responseText;
}

function nsResolver(prefix) {
  var ns = {
    'wsdm' : 'http://extreme.indiana.edu/wsdm/',
    'man': 'http://extreme.indiana.edu/manager/',
    'lead': 'http://extreme.indiana.edu/leadmanager/'
  };
  return ns[prefix] || null;
}

function processShellSubmit(){
	
	//document.getElementById('shell_out').innerHTML = "Test value";
	
	var xmlDoc = restCall("hasthi/forward/http_129.79.240.90_38143/hasthi/resources");	
	//var nsResolver = xmlDoc.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
	
	//var it = xmlDoc.evaluate('//man:resource@name', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );
	var it = xmlDoc.evaluate('//man:resource', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );
	var result = "Initial";
	try {
	  var thisNode = it.iterateNext();
	  
	  while (thisNode) {
	    result = result +" "+ thisNode.getAttribute("name"); //textContent 
	    thisNode = it.iterateNext();
	  }	
	  //alert('Called '+result + " "+ xmlDoc);
	  document.getElementById('shell_out').innerHTML = result;
	}
	catch (e) {
	  alert( 'Error: Document tree modified during iteration ' + e );
	}
}


function init(){
	//window.setInterval(updateSystemState, 30000);
}

function updateSystemState(){
	//coorAddress.replace(":","_").replace("http://","");
	//var xmlDoc = restCall("hasthi/forward/"+coorAddress+"/hasthi/systemStatus");
	var xmlDoc = restCall("/hasthi/systemStatus");
	
	var params =new Array("managerCount","resourceCount","memoryUsage");
	for(p in params){
		var ele = findFirstElement(xmlDoc,"//man:"+params[p],nsResolver);
		if(ele != null){
			document.getElementById(params[p]).innerHTML = ele.textContent;
		}else{
			alert("Parameter "+ p + " is null");
		}
	}
	
	var map = new Array();
	var index = 0;
	var it = xmlDoc.evaluate('//man:queryResults', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );
	var thisNode = it.iterateNext();
	while (thisNode) {
	//alert(thisNode.getElementsByTagName('man:query'));
    	var query = findFirstElementContent(thisNode,'http://extreme.indiana.edu/manager/','query');
    	query = query.replace(/BusyState|IdleState/,"Functional");
    	query = query.replace(/StoppedState|CrashedState|FaultyState|UnRepairableState|RepairedState|RepairingState/,"Faulty");
    	query = query.replace(/type=/,"").replace(/,state=/,'_');	
    	
    	var count =  findFirstElementContent(thisNode,'http://extreme.indiana.edu/manager/','count');
    	var val;
    	if(map[query]){
    		val = parseInt(map[query]) + parseInt(count);
    	}else{
    		map[query] = count;
    		val = parseInt(count);
    	}
    	
    	document.getElementById(query).innerHTML = val;
    	//map.push(query : count);
    	thisNode = it.iterateNext();
    }	
    
    
    var tm = new Array();
    
    tm['a'] = 10;
    //alert(tm['a']);
    /*
    var type =new Array("Service","ComputeNode","Host","TransientService");
    var state =new Array("Functional","SaturatedState", "Faulty");
    
    for(i in type){
    	for(j in state){
    		var key = type[i]+"_"+state[j];
    		var val = map[key];
    		if(val){
    			alert(key +" = "+val);
    			document.getElementById(key).innerHTML = val;
    		}
    	}
    }
    */
    //alert(xml2str(xmlDoc));
    var coorele = findFirstElement(xmlDoc,"//man:coordinatorAddress/man:soapAddress",nsResolver);
    if(coorele != null){
    	g_cooraddr = coorele.textContent;
    	updateWorkflowstat(coorele.textContent);
    }else{
    	alert("Error, Coordiantor is Null");
    }
    
    
    
}

function findFirstElementContent(node,nsuri,name){
	var x= node.getElementsByTagNameNS(nsuri,name);
	if(x.length > 0){
		return x[0].textContent
	}else{
		alert(x + " is zero length");
		return null;
	}
}

function findFirstElement(xmlDoc,xpath,nsResolver){
	//alert(xpath);
	var it = xmlDoc.evaluate(xpath, xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );
	return it.iterateNext();
}


function updateWorkflowstat(coorAddress){
	var url = createFwdAddress(coorAddress) 
		+"/hasthi/ResolveServiceDependancy/"+escape("{http://extreme.indiana.edu/lead}LeadInformationProxy"); 
	var xmlDoc = restCall(url);
	if(xmlDoc != null){
		//alert(xml2str(xmlDoc));
	}else{
		//alert("Response is Null for "+ url);
		
	}
	
	var wfstatDoc = restCall("/hasthi/forward/http_linbox3_6007/hasthi/GetWorkflowStaistics/72");
	if(wfstatDoc != null){
		//alert(xml2str(wfstatDoc));
		var params =new Array("workflowsRunning","workflowsFinished","workflowsFailed","workflowsPaused","failureCount");
		for(p in params){
			var ele = findFirstElement(wfstatDoc,"//lead:"+params[p],nsResolver);
			if(ele != null){
				document.getElementById(params[p]).innerHTML = ele.textContent;
			}else{
				alert("Parameter "+ p + " is null");
			}
		}
		
		var it = xmlDoc.evaluate('//lead:failureDistribution', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );
			var table = document.getElementById('wf_faildata_table');
			removeAllRowsFromTable(table);			
			try {
			  var thisNode = it.iterateNext();
			  while (thisNode) {
				var row = table.insertRow(0);
				var message = thisNode.getAttribute('faultMessage');
				var freq = thisNode.getAttribute('faultFrequency');
				row.innerHTML = '<td>'+message+'</td><td>'+freq+'</td>';
			    thisNode = it.iterateNext();
			  }	
			}
			catch (e) {
			  alert( 'Error: Document tree modified during iteration ' + e );
			}
		
		
	}else{
		//alert("Response is Null for "+ url);
	}
}


function updateResourcesList(){
	if(g_cooraddr != null){
		var url = createFwdAddress(g_cooraddr) 
			+"/hasthi/ExecuteQuery/"+escape('QueryResources('
				+document.getElementById('rb_category').value +","+ document.getElementById('rb_resource_name').value+")"); 
		var xmlDoc = restCall(url);
		if(xmlDoc != null){
			var it = xmlDoc.evaluate('//man:resource', xmlDoc, nsResolver, XPathResult.ANY_TYPE, null );
			var table = document.getElementById('resourcePannel');
			removeAllRowsFromTable(table);			
			try {
			  var thisNode = it.iterateNext();
			  while (thisNode) {
				var row = table.insertRow(0);
				var qname = toQName(thisNode,thisNode.textContent);
				row.innerHTML = '<td><a href="'+g_cooraddr +'/hasthi/resource/'+escape(qname)+'">'
					+ qname.replace(/\{.*\}/, "")+'</td>';
			    thisNode = it.iterateNext();
			  }	
			}
			catch (e) {
			  alert( 'Error: Document tree modified during iteration ' + e );
			}
		}else{
			//alert("Response is Null for "+ url);
		}
	}else{
		alert("No Coordinator found yet");
	}
}

function toQName(element,name){
	var tokens = name.split(":");
	if(tokens.length == 1){
		return name;
	}else if(tokens.length > 1){
		return '{'+element.lookupNamespaceURI(tokens[0])+'}'+tokens[1];
	}else{
		throw "wrong name to lookup QName "+ name;
	}
}
function removeAllRowsFromTable(table){
	while(table.rows.length > 0){
		table.deleteRow(0);
	}
	
}

function createFwdAddress(address){
	return "/hasthi/forward/"+ address.replace(/\//g,"").replace(/:/g,"_");
}

function xml2str(xmlobject){
	return (new XMLSerializer()).serializeToString(xmlobject);
}




